import 'package:lovify/core/network/model/pagination.dart';
import 'package:lovify/core/network/model/response_entity.dart';
import 'package:lovify/core/utils/api_client.dart';

abstract class BaseService<T> {
  final ApiClient apiClient = ApiClient();
  final String endpoint;
  final Map<String, dynamic> Function(T) toJson;
  final T Function(Object? json) fromJson;

  BaseService({
    required this.endpoint,
    required this.toJson,
    required this.fromJson,
  });

  Future<ResponseEntity<T>> create(T entity) async {
    final response = await apiClient.post(endpoint, body: toJson(entity));
    return ResponseEntity.fromJson(response, fromJson);
  }

  Future<ResponseEntity<T>> findById(String id) async {
    final response = await apiClient.get('$endpoint/$id');
    return ResponseEntity.fromJson(response, fromJson);
  }

  Future<ResponseEntity<Pagination<T>>> findAll(
      {int page = 0, int size = 10}) async {
    final response = await apiClient
        .get(endpoint, params: {'page': '$page', 'size': '$size'});
    return ResponseEntity.fromJson(
      response, (json) => Pagination.fromJson(
        json as Map<String, dynamic>, fromJson
      )
    );
  }

  Future<ResponseEntity<T>> update(String id, T entity) async {
    final response =
        await apiClient.put('$endpoint/$id', body: toJson(entity));
    return ResponseEntity.fromJson(response, fromJson);
  }

  Future<void> delete(String id) async {
    await apiClient.delete('$endpoint/$id');
  }
}
